package com.bawei.viewmodel_livedata_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

/**
 *  举例：activity数字显示，定时器每次数字+1显示
 */
public class MainActivity2 extends AppCompatActivity {
    private TextView mTextView;
    private NumViewModel2 mNumViewModel2;
    private  Timer timer = new Timer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        mTextView = findViewById(R.id.tv);
        mNumViewModel2 = new ViewModelProvider(this).get(NumViewModel2.class);
        /***************观察LiveData对象变化************/
        mNumViewModel2.getNum().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                mTextView.setText(integer+"");
            }
        });
        initTimer();



    }
    //定时器：更新livedata数据
    private void initTimer() {
       timer.schedule(new TimerTask() {
           @Override
           public void run() {
               //子线程设置新的值：postValue
               int num = mNumViewModel2.getNum().getValue()+1;
               mNumViewModel2.getNum().postValue(num);

           }
       },1000,1000);
    }
}